package com.starblink.imgsearch.result.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.starblink.android.basic.adapter.BaseVH
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.fragment.BaseTVMLazyLoadingFragment
import com.starblink.android.basic.data.model.product.ProductFWrap
import com.starblink.android.basic.ext.bindProductFeeds
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.ext.string
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.basic.style.R
import com.starblink.imgsearch.databinding.CellForyouTitleBinding
import com.starblink.imgsearch.databinding.CellResultTipBinding
import com.starblink.imgsearch.databinding.FragmentResultTabBinding
import com.starblink.imgsearch.result.data.ResultBrandModel
import com.starblink.imgsearch.result.data.ResultPriceModel
import com.starblink.imgsearch.result.ui.cell.ForYouTitleCell
import com.starblink.imgsearch.result.ui.cell.ResultTipCell
import com.starblink.library.widget.loading.GoodsCardLoadingCell
import com.starblink.library.widget.product.ProductCardScene
import com.starblink.library.widget.product.RecommendProductCardCell
import com.starblink.library.widget.product.SimpleProductCardCell
import com.starblink.rocketreserver.fragment.PicSearchResultF

/**
 * 图搜结果子页（每个Tab对应一个子页）
 */
internal class ResultTabFragment :
    BaseTVMLazyLoadingFragment<FragmentResultTabBinding, TabViewModel>() {

    companion object {
        fun newInstance(
            position: Int,
            region: String,
            picUrl: String,
            postPicAiId: String? = null,
            list: List<ProductFWrap>? = null,
            selectOtherCountryFlag: Boolean? = null,
            currentCountryIsolateFlag: Boolean? = null,
            mTopTotalNum: Int = 0,
            brandMapList: HashMap<Int, ArrayList<ResultBrandModel>>,
            priceMapList: HashMap<Int, ResultPriceModel>,
            searchWordMapList: HashMap<Int, List<PicSearchResultF.SearchWordList?>?>
        ) = ResultTabFragment().apply {
            arguments = Bundle().apply {
                putInt("position", position)
            }
            this.list = list
            this.picUrl = picUrl
            this.region = region
            this.postPicAiId = postPicAiId
            this.selectOtherCountryFlag = selectOtherCountryFlag
            this.currentCountryIsolateFlag = currentCountryIsolateFlag
            this.mTopTotalNum = mTopTotalNum
            this.brandMapList = brandMapList
            this.priceMapList = priceMapList
            this.searchWordMapList = searchWordMapList
        }

        private const val TAG = "ResultTabFragment"
    }

    private var list: List<ProductFWrap>? = null

    var picUrl = ""

    var region = ""

    var postPicAiId: String? = null

    var selectOtherCountryFlag: Boolean? = null

    var mTopTotalNum: Int = 0

    var currentCountryIsolateFlag: Boolean? = null

    var bottomSheetExpand = false

    var brandMapList: HashMap<Int, ArrayList<ResultBrandModel>>? = null
    var priceMapList: HashMap<Int, ResultPriceModel>? = null
    var searchWordMapList: HashMap<Int, List<PicSearchResultF.SearchWordList?>?>? = null
    private val tabPosition by lazyOnNone {
        arguments?.getInt("position") ?: 0
    }

    private var pageTrackTag: String? = null

    private val adapter by lazyOnNone {
        object : MutableAdapter(viewModel.adapterList) {

            override fun onViewDetachedFromWindow(holder: BaseVH<*>) {
                super.onViewDetachedFromWindow(holder)
            }

            override fun onBindViewHolder(holder: BaseVH<*>, position: Int) {
                if (holder is SimpleProductCardCell) {
                    holder.pageTrackTag = this@ResultTabFragment.hashCode()
                        .toString() + (if (pageTrackTag.isNullOrEmpty()) "" else pageTrackTag)
                } else if (holder is RecommendProductCardCell) {
                    holder.pageTrackTag = this@ResultTabFragment.hashCode()
                        .toString() + (if (pageTrackTag.isNullOrEmpty()) "" else pageTrackTag)
                }
                super.onBindViewHolder(holder, position)
            }

        }.apply {
            addVhDelegate {
                RecommendProductCardCell(
                    viewBinding.refresher,
                    viewBinding.recycler,
                    it,
                    ProductCardScene.IMAGE_SEARCH_RECOMMEND,
                    pageTrackTag = this@ResultTabFragment.hashCode().toString(),
                )
            }
            addVhDelegate {
                SimpleProductCardCell(
                    viewBinding.refresher,
                    viewBinding.recycler,
                    it,
                    ProductCardScene.IMAGE_SEARCH,
                    pageTrackTag = this@ResultTabFragment.hashCode().toString(),
                )
            }
//            addVhDelegate {
//                SeeMoreCell(CellSeeeMoreBinding.inflate(it.inflater)) {
//                    binding.btn.isEnabled = false
//                    viewModel.loadMoreContent()
//                }
//            }
            addVhDelegate {
                ForYouTitleCell(CellForyouTitleBinding.inflate(it.inflater))
            }
            addVhDelegate {
                ResultTipCell(CellResultTipBinding.inflate(it.inflater))
            }
        }
    }


    private val loadAdapter = MutableAdapter(
        GoodsCardLoadingCell.LOADING_DATA
    ).apply {
        addVhDelegate {
            GoodsCardLoadingCell(it)
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }


    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentResultTabBinding = FragmentResultTabBinding.inflate(inflater)

    override fun startObserve() {
        viewModel.resultLD.observe(this) {
            if (viewModel.pageNo == 1) {
                if (it.isEmpty()) {
                    showEmpty()
                } else {
                    viewModel.adapterList.run {
//                        add(0, viewModel.tipItem.apply {
//                            visible = true
//                            firstScore = it.firstOrNull()?.productF?.score ?: 0.0
//                        })
                        addAll(it)
//                        add(viewModel.seeMoreItem.apply {
//                            visible = true
//                        })
                        adapter.refreshAll()
                    }
                    showContent()
                }
            } else {
                showContent()
//                val seeIndex = viewModel.seeMoreItemIndex()
//                if (it.isEmpty() && seeIndex > -1) {
//                    viewModel.adapterList.removeAt(seeIndex)
//                    adapter.notifyItemRemoved(seeIndex)
//                    return@observe
//                } else {
//                    viewModel.seeMoreItem.enable = true
//                    adapter.notifyItemChanged(seeIndex)
//                }
//                viewModel.adapterList.addAll(seeIndex, it)
//                adapter.notifyItemRangeChanged(seeIndex, it.size)
            }
        }
        viewModel.recommendLD.observe(this) { it ->
            val forUIndex = viewModel.forUItemIndex()
            if (it.isNotEmpty() && forUIndex < 0) {
                viewModel.adapterList.add(viewModel.forUItem)
            }
            if (viewModel.recommendPageNo == 1) {
                val oldSize = viewModel.adapterList.size
                viewModel.adapterList.run {
                    addAll(it)
                    if (forUIndex > 0) {
                        adapter.notifyItemRangeChanged(forUIndex, it.size)
                    } else {
                        adapter.notifyItemRangeChanged(oldSize, it.size)
                    }
                }
            } else {
                viewModel.adapterList.addAll(it)
                adapter.notifyItemRangeChanged(viewModel.adapterList.size - 1, it.size)
            }
            if (it.isEmpty()) {
                viewBinding.refresher.finishLoadMoreWithNoMoreData()
//                viewBinding.refresher.setNoMoreData(true)
            }
            //偶现第一个在右边的情况
        }
        viewModel.loadStateLD.observe(this) { it ->
            if (it == TabViewModel.LOAD_STATE_FINISH) {
                viewModel.forUItemIndex().takeIf { it > -1 }?.run {
                    adapter.notifyItemChanged(this)
                }
                viewBinding.refresher.finishLoadMore()
            }
        }


        FlowBus.with<Int>(FlowConst.IMG_SEARCH_BRAND_ITEM_CLICK)
            .register(this) { pageIndex ->
                if (pageIndex == viewModel.tabPosition) {
                    reload()
                }
            }
    }

    override fun initData() {

        viewModel.postPicAiId = postPicAiId
        viewModel.picUrl = picUrl
        viewModel.regin = region
        viewModel.selectOtherCountryFlag = selectOtherCountryFlag
        viewModel.currentCountryIsolateFlag = currentCountryIsolateFlag
        viewModel.mTopTotalNum = mTopTotalNum
        viewModel.brandMapList = brandMapList
        viewModel.tabPosition = tabPosition
        viewModel.priceMapList = priceMapList
        viewModel.searchWordMapList = searchWordMapList
        if (tabPosition != 0) {
            searchWordMapList!![tabPosition] = arrayListOf()
        }

        list?.let {
            viewModel.products.addAll(it)
        }
        viewModel.initAdapterList()
        adapter.refreshAll()
    }

    private fun initView() {
        showStateSuccess()
        viewBinding.recycler.bindProductFeeds(adapter)
//        viewBinding.recycler.bindFeedsNoviceHelper(requireActivity()) {
//            bottomSheetExpand
//        }
        viewBinding.loading.bindProductFeeds(loadAdapter)
        viewBinding.refresher.run {
            setEnableAutoLoadMore(true)
            setEnableLoadMoreWhenContentNotFull(false) // 重要，不满一屏时上拉加载更多会导致手势冲突
            setEnableNestedScroll(false)
            setEnableRefresh(false)
            setEnableLoadMore(true)
            setOnLoadMoreListener {
                viewModel.loadMoreRecData()
            }
        }
        viewBinding.emptyView.onBtnClick = {
            if (viewModel.selectOtherCountryFlag == true) {
                viewModel.run {
                    saleableCountryFlag = false
                    resetData()
                    loadInitData()
                    showLoading()
                }
            } else {
                mActivity.finish()
            }
        }
    }

    override fun onLazyInitData() {
        if (viewModel.products.isNotEmpty()) {
            viewModel.pageNo++
            viewModel.recommendPageNo = 0
            viewModel.loadMoreRecData()
            showContent()
        } else {
            if (tabPosition == 0) {
                showEmpty()
            } else {
                showLoading()
                viewModel.loadInitData()
            }
        }
    }

    private fun showContent() {
        viewBinding.emptyWrapper.gone()
        viewBinding.loading.gone()
        viewBinding.recycler.visible()

        if (viewModel.pageNo == 1) {
            pageExposure(
                SpmPageDef.GdsAndPostItemTab
            )
        }
    }

    private fun showLoading() {
        viewBinding.emptyWrapper.gone()
        viewBinding.recycler.gone()
        viewBinding.loading.visible()
    }

    private fun showEmpty() {
        viewBinding.emptyWrapper.visible()
        viewBinding.recycler.gone()
        viewBinding.loading.gone()
        viewBinding.emptyView.run {

            //是否显示查询其他国家的按钮
            if (viewModel.selectOtherCountryFlag == true) {
                hideTitle = false
                titleText = string(R.string.img_res_empty_title)
                text2 = string(R.string.img_res_empty)
                hideText1 = true
                hideText2 = false
                hideTitle = false
                btnShown = true
                btnText = string(R.string.search_other_countries)
            } else {
                hideTitle = false
                titleText = string(R.string.img_res_empty_title_1)
                text2 = string(R.string.img_res_empty_1)
                hideText1 = true
                hideText2 = false
                hideTitle = false
                btnShown = true
                btnText = string(R.string.try_again)
            }
        }


    }

    fun reload() {
        view ?: return
        viewModel.picUrl = picUrl
        viewModel.regin = region
        viewModel.saleableCountryFlag = TabViewModel.DEFAULT_COUNTRY_FLAG
        selectOtherCountryFlag = null
        currentCountryIsolateFlag = null
        viewModel.selectOtherCountryFlag = null
        viewModel.currentCountryIsolateFlag = null
        viewModel.resetData()
        viewModel.loadInitData()
        viewBinding.refresher.setNoMoreData(false)
        showLoading()
        pageTrackTag = if (pageTrackTag.isNullOrEmpty()) "1" else pageTrackTag + "1"
    }

    override fun initView(view: View) {

    }

    override fun initLoad() {

    }

    override fun onResume() {
        super.onResume()
        pageExposure(
            SpmPageDef.ImgSearch2Route,
        )
        if (viewModel.products.isNotEmpty()) {
            pageExposure(
                SpmPageDef.GdsAndPostItemTab,
            )
        }
    }

    override fun onPause() {
        super.onPause()
        pageDisappear(
            SpmPageDef.ImgSearch2Route,
        )
        if (viewModel.products.isNotEmpty()) {
            pageDisappear(
                SpmPageDef.GdsAndPostItemTab,
            )
        }
    }

}